const http = require('http')
const fs = require('fs')
const url = require('url')

http.createServer((req, res) => {
    const { pathname } = url.parse(req.url)
    console.log(req.method, req.url)
    switch (pathname) {
        case "/api":
            const d = { name: '张安' }
            return res.end(200, JSON.stringify(d))
        case '/':
            const data = fs.readFileSync('./index.html');
            return res.end(data)
        case "/libs/logo_sm.png": // 强制缓存
            res.writeHead(200, {
                // Expires强制缓存过期时间（绝对时间）
                Expires: new Date('2021-6-28 22:14:10').toUTCString()
            })
            return res.end(fs.readFileSync('./libs/logo_sm.png'))
        case "/libs/download.png": // 强制缓存
            res.writeHead(200, {
                // 滑动时间，单位是秒
                'Cache-Control': 'max-age=10'
            })
            return res.end(fs.readFileSync('./libs/download.png'))
        case "/libs/bg_loading.gif": // 协商缓存 last-modified
            const { mtime } = fs.statSync('./libs/bg_loading.gif');
            res.setHeader('last-modified', mtime.toUTCString())
            res.setHeader('Cache-Control', 'no-cache')
            const ifModifiedSince = req.headers['if-modified-since']
            if (ifModifiedSince === mtime.toUTCString()) {
                res.statusCode = 304
                return res.end()
            }
            res.end(fs.readFileSync('./libs/bg_loading.gif'))
        // case "/libs/watch.png": // ETag
        //     const file = 
        default:
            res.statusCode = 404
            return res.end()
    }
}).listen(3000, () => console.log('http://localhost:3000'))